import { Injectable } from '@angular/core';
import {Observable} from "rxjs/internal/Observable";
import {HttpClient} from "@angular/common/http";
import {MatSnackBar} from "@angular/material";
import {ApiUrls} from "../../api.urls";
import {Router} from "@angular/router";
import {AuthInfo} from "../../entity/auth.entity";
import {LoggerService} from "@ngx-toolkit/logger";

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  token: string;
  authInfo: AuthInfo;
  loginUrl: string = ApiUrls.buildUrl(ApiUrls.login);
  authUrl: string = ApiUrls.buildUrl(ApiUrls.auth);

  constructor(
    private httpClient: HttpClient,
    private router: Router,
    private snackBar: MatSnackBar,
    private logger: LoggerService) {
    //如果已保存token
    let jwt = window.localStorage.getItem("token");
    if(jwt){
      this.logger.info("localtoken is:"+jwt);
      this.token = jwt;
    }
  }

  //登录逻辑
  saveTokenByLogin(loginFormData: any): void{
    // console.log(this.loginUrl);
    this.httpClient.post(this.loginUrl, loginFormData).subscribe(
      data => {
        this.token = data["token"];
        window.localStorage.setItem("token", this.token);

      },
      error => {
        this.logger.info(error);
        this.snackBar.open(error["error"]["errorMsg"],"",{
          duration: 3000
        });
      },
      () => this.router.navigateByUrl("nav")
    );
    return
  }

  getAuthInfo(): Observable<AuthInfo>{
    return this.httpClient.get<AuthInfo>(this.authUrl);
  }

  clearAuthInfo(): void{
    this.token = null;
    this.authInfo = null;
    if(window.localStorage.getItem("token")){
      window.localStorage.removeItem("token");
    }
    this.router.navigateByUrl("/login");
  }
}
